/* eslint-disable no-undef */

import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import styleImport from 'vite-plugin-style-import'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  const proxyPrefix = env['VITE_APP_PROXY_PREFIX']

  return {
    plugins: [
      vue(),
      vueJsx(),
      legacy({ targets: ['defaults', 'not IE 11'] }), // vue3 不支持ie11

      // 按需加载
      styleImport({
        libs: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => {
              return `ant-design-vue/es/${name}/style/index`
            },
          },
        ],
      }),
    ],
    resolve: {
      alias: { '@': path.resolve(__dirname, './src') },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          // 注入全局变量
          additionalData: `@import '@/styles/variables.less';`,
          // 修改 antd 默认的变量
          modifyVars: { '@primary-color': '@theme-color' },
        },
      },
    },

    server: {
      port: 7471,
      host: true,
      proxy: {
        [proxyPrefix]: {
          target: 'https://cnodejs.org/api/v1',
          changeOrigin: true,
          rewrite: (p) => p.replace(new RegExp(`^${proxyPrefix}`), ''),
        },

        // 自定义代理(需要符合自定义代理规则,会影响'@/utils/http.js'中的'withProxy')
        // 在这里没有做校验,是为了放宽自定义的配置
        '/api-abc': {
          target: 'https://cnodejs.org/api/v1',
          rewrite: (p) => p.replace(/^\/api-abc/, ''),
        },
      },
    },

    base: './',
  }
})
